<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>语音聊天 Demo</title>
</head>
<body>
<h3>按住按钮说话</h3>
<button id="recBtn" onmousedown="startRec()" onmouseup="stopRec()" style="width:120px;height:50px;">按住说话</button>
<audio id="player" controls style="display:none;"></audio>

<script>
    let mediaRec, chunks = [];
    const player = document.getElementById('player');

    async function startRec() {
        chunks = [];
        const stream = await navigator.mediaDevices.getUserMedia({audio:true});
        mediaRec = new MediaRecorder(stream);
        mediaRec.ondataavailable = e => chunks.push(e.data);
        mediaRec.onstop = async () => {
            const blob = new Blob(chunks, {type:'audio/webm'});
            await sendAsr(blob);
            stream.getTracks().forEach(t => t.stop());
        };
        mediaRec.start();
    }

    async function stopRec() {
        mediaRec.stop();
    }

    async function sendAsr(blob) {
        const form = new FormData();
        form.append('audio', blob, 'rec.webm');
        const res = await fetch('/api/asr', {method:'POST', body:form});
        const text = await res.text();
        console.log('识别：', text);

        // 发给 Java 做 LLM 答案（这里直接 mock）
        const ansRes = await fetch('/api/chat', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({question:text})
        });
        const answer = await ansRes.text();
        console.log('回答：', answer);

        // 拿到 tts 音频
        const ttsRes = await fetch('/api/tts', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({text:answer})
        });
        const wavBlob = await ttsRes.blob();
        const url = URL.createObjectURL(wavBlob);
        player.src = url;
        player.style.display = 'block';
        player.play();
    }
</script>
</body>
</html>
